package daobeauty.interceptor.returntype.executor.query;

import java.util.Collection;

import org.hibernate.Query;

import daobeauty.dao.Limiting;
import daobeauty.dao.Sorting;
import daobeauty.interceptor.returntype.executor.ExecutionStrategy;
import daobeauty.interceptor.returntype.handler.ReturnTypeHandler;
import daobeauty.interceptor.returntype.handler.ReturnTypeHandlerManager;

/**
 * Executes queries corresponding to the given limiting and uses a returntypehandler
 * to generate appropriate return type.
 * 
 * @author M. Serhat Cinar
 *
 */
public class QueryExecutor implements ExecutionStrategy{
	private ReturnTypeHandler returnTypeHandler;
	private QueryExecutionStrategy queryExecutionStartegy;
	
	public QueryExecutor(Class returnType){
		returnTypeHandler = ReturnTypeHandlerManager.getByOutType(returnType);
		if (Collection.class.isAssignableFrom(returnType) || Object[].class.isAssignableFrom(returnType)){
			queryExecutionStartegy = ListQueryExecutionStrategy.INSTANCE; 
		}
		else{
			queryExecutionStartegy = UniqueResultQueryExecutionStrategy.INSTANCE;
		}
	}
	
	public Object execute(Query query, Limiting limiting){
		return queryExecutionStartegy.execute(returnTypeHandler, query, limiting);
	}

	public Object execute(Object criteriaOrQuery, Limiting limiting, Sorting sorting) {
		return execute((Query) criteriaOrQuery, limiting);
	}
}
